package jbl.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jbl.dao.LogDaoI;
import jbl.io.excel.LogExcel;
import jbl.model.Code_log;
import jbl.pageModel.DataGrid;
import jbl.pageModel.Log;
import jbl.service.LogServiceI;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service("logService")
public class LogServiceImpl implements LogServiceI {
	/**
	 * Logger for this class
	 */
	private LogDaoI logDao;
	
	@Autowired
	public void setLogDao(LogDaoI logDao) {
		this.logDao = logDao;
	}
	
	@Override
	public DataGrid dataGrid(Log log) {
		// TODO Auto-generated method stub
		DataGrid dg = new DataGrid();
		try {
			List<Log> logList = new ArrayList<Log>();
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " From Code_log t where 1=1 ";
			String totalHql = "select count(*) " + hql;
			hql = addWhere(hql, log, params);
			hql = addOrder(hql , log);
			List<Code_log> list = logDao.find(hql,params,log.getPage(), log.getRows()); 
			if(null != list && list.size() > 0){
				for(Code_log t : list){
					Log Log1 = new Log();
					BeanUtils.copyProperties(t, Log1);
					logList.add(Log1);
				}
			}
			dg.setRows(logList);
			dg.setTotal(logDao.count(totalHql));
		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return dg;
	}
	
	private String addOrder(String hql , Log log){
		if(null != log.getSort()){
			hql += " order by t."+log.getSort() +" " + log.getOrder();
		}
		return hql;
	}
	
	private String addWhere(String hql , Log log, Map<String, Object> params){
		if(null != log.getUser() && !"".equals(log.getUser())){
			hql += " and t.user like '%"+log.getUser()+"%'";
		}
		if(log.getStartCjsj()!=null&&!log.getStartCjsj().equals("")){
			hql+=" and t.cjsj>=:start";
			params.put("start",log.getStartCjsj());
		}
		if(log.getEndCjsj()!=null&&!log.getEndCjsj().equals("")){
			hql+=" and t.cjsj<=:end";
			params.put("end",log.getEndCjsj());
		}
		return hql;	
	}
	
	@Override
	public List<LogExcel> getLogList(Log log) {
		// TODO Auto-generated method stub
		List<LogExcel> logList = new ArrayList<LogExcel>();
		try {
			
			Map<String, Object> params = new HashMap<String, Object>();
			String hql = " From Code_log t where 1=1 ";
			hql = addWhere(hql, log, params);
			List<Code_log> list = logDao.find(hql,params); 
			int xh = 0;
			if(null != list && list.size() > 0){
				for(Code_log t : list){
					LogExcel Log1 = new LogExcel();
					BeanUtils.copyProperties(t, Log1);
					Log1.setXh(++xh);
					logList.add(Log1);
				}
			}

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}
		return logList;
	}
}
